<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-alert title="注意:只能为三级菜单修改分类" :closable="false" type="warning" show-icon> </el-alert>
      选择商品分类
      <el-cascader v-model="value" :options="catesList" :props="cascaserProps" @change="handleChange"></el-cascader>
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="first"></el-tab-pane>
        <el-tab-pane label="静态属性" name="second"></el-tab-pane>
      </el-tabs>
      <el-button :disabled="btndisabled" type="primary" v-if="this.activeName == 'first'" @click="addParams"
        >添加动态参数</el-button
      >
      <el-button :disabled="btndisabled" type="primary" v-else @click="addParams">添加静态属性</el-button>
      <!-- 动态参数列表 -->
      <!-- <el-table border stripe :data="onlyList" style="width: 100%">
        <el-table-column type="expand" label="" width="180"> </el-table-column>
        <el-table-column type="index" label="#" width="180"> </el-table-column>
        <el-table-column prop="attr_name" label="参数名称"> </el-table-column>
        <el-table-column label="操作">
          <el-button type="primary" size="mini" icon="el-icon-edit">修改</el-button>
          <el-button type="danger" size="mini" icon="el-icon-delete">删除</el-button>
        </el-table-column>
      </el-table> -->

      <!-- 静态属性 -->
      <el-table border stripe :data="this.activeName == 'first' ? manyList : onlyList" style="width: 100%">
        <el-table-column type="expand" width="180">
          <template slot-scope="scope">
            <el-tag
              closable=""
              v-for="(item, index) in scope.row.attr_vals"
              :key="index"
              @close="handleClose(index, scope.row)"
            >
              {{ item }}
            </el-tag>
            <el-input
              class="input-new-tag"
              v-if="scope.row.inputVisible"
              v-model="scope.row.inputValue"
              ref="saveTagInput"
              size="small"
              @keyup.enter.native="handleInputConfirm"
              @blur="handleInputConfirm(scope.row)"
            >
            </el-input>
            <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#" width="180"> </el-table-column>
        <el-table-column prop="attr_name" label="参数名称"> </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" icon="el-icon-edit" @click="edit(scope.row)">修改</el-button>
            <el-button type="danger" size="mini" icon="el-icon-delete" @click="dele(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加动态参数或者静态属性面板 -->
    <el-dialog
      :title="this.activeName == 'first' ? '添加动态参数' : '添加静态属性'"
      :visible.sync="addFormVisible"
      width="50%"
      @close="addFormClosed"
    >
      <el-form :model="addForm" :rules="addrules" ref="addFormRef" label-width="150px" class="demo-ruleForm">
        <el-form-item :label="this.activeName == 'first' ? '添加动态参数' : '添加静态属性'" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmAdd">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改动态参数或者静态属性面板 -->
    <el-dialog
      :title="this.activeName == 'first' ? '修改动态参数' : '修改静态属性'"
      :visible.sync="editFormVisible"
      width="50%"
      @close="editFormClosed"
    >
      <el-form :model="editForm" :rules="addrules" ref="editFormRef" label-width="150px" class="demo-ruleForm">
        <el-form-item :label="this.activeName == 'first' ? '修改动态参数' : '修改静态属性'" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmEdit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      catesList: [],
      value: [],
      activeName: 'first',
      onlyList: [],
      manyList: [],
      btndisabled: false,
      addFormVisible: false,
      editFormVisible: false,
      edit_id: '',
      addForm: {
        attr_name: '',
      },
      addrules: {
        attr_name: [{ required: true, message: '请输入参数名', trigger: 'blur' }],
      },
      editForm: {
        attr_name: '',
      },
      cascaserProps: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children',
        expandTrigger: 'hover',
      },
    }
  },
  created() {
    this.getAllCates()
  },
  methods: {
    async getAllCates() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取列表失败')
      this.$message.success('获取分类列表成功')
      this.catesList = res.data
      if (this.value.length == 0) this.btndisabled = true
      console.log(res)
    },

    //获取动态参数或者是静态属性
    async getParamsList(type) {
      const { data: res } = await this.$http.get(`categories/${this.value[2]}/attributes`, {
        params: {
          sel: type,
        },
      })
      if (res.meta.status !== 200) return this.$message.error('获取列表失败')
      console.log(res)

      res.data.forEach((element) => {
        element.attr_vals = element.attr_vals.length == 0 ? [] : element.attr_vals.split(' ')
        //给每个item项设置inputvaisable属性
        element.inputVisible = false
        element.inputValue = ''
      })
      if (type == 'only') this.onlyList = res.data
      else {
        this.manyList = res.data
      }
      this.$message.success('获取列表成功')

      console.log(res)
    },
    async handleChange() {
      if (this.value.length < 3) {
        this.value = []
        this.btndisabled = true
        ;(this.onlyList = []), (this.manyList = [])
        return
      }
      this.btndisabled = false
      this.getParamsList('many')
    },
    async handleClick() {
      if (this.value.length == 0) return
      if (this.activeName == 'first') this.getParamsList('many')
      if (this.activeName == 'second') this.getParamsList('only')
    },

    //添加动态参数或者静态属性的面板
    addParams() {
      this.addFormVisible = true
    },

    //添加属性面板关闭
    addFormClosed() {
      this.$refs.addFormRef.resetFields()
    },

    //确定添加
    confirmAdd() {
      let attr_sel = this.activeName == 'first' ? 'many' : 'only'
      console.log(attr_sel)
      this.$refs.addFormRef.validate(async (val) => {
        if (val) {
          const { data: res } = await this.$http.post(`categories/${this.value}/attributes`, {
            attr_name: this.addForm.attr_name,
            attr_sel: attr_sel,
          })
          console.log(res)
          if (res.meta.status !== 201) return this.$message.error('添加失败')
          this.$message.success('添加成功')
          this.addFormVisible = false
          this.handleClick()
        }
      })
    },

    //点击编辑按钮, 弹出修改属性或者参数面板
    edit(role) {
      this.editFormVisible = true
      this.editForm.attr_name = role.attr_name
      this.edit_id = role.attr_id
    },

    //删除属性或者参数
    async dele(role) {
      const confirm = await this.$confirm('此操作将永久删除该属性, 是否继续?', '提示', {
        type: 'warning',
      }).then((err) => err)

      if (confirm == 'confirm') {
        const { data: res } = await this.$http.delete(`categories/${this.value}/attributes/${role.attr_id}`)
        if (res.meta.status !== 200) return this.$message.error('获取列表失败')
        this.$message.success('删除成功')
        this.handleClick()
      }
    },

    //确定修改参数或者属性Q
    confirmEdit() {
      let attr_sel = this.activeName == 'first' ? 'many' : 'only'
      this.$refs.editFormRef.validate(async (val) => {
        if (!val) return this.$message.error('请填写参数')
        const { data: res } = await this.$http.put(`categories/${this.value}/attributes/${this.edit_id}`, {
          attr_name: this.editForm.attr_name,
          attr_sel: attr_sel,
        })
        if (res.meta.status !== 200) return this.$message.error('获取列表失败')
        this.$message.success('修改成功')
        this.editFormVisible = false
        this.handleClick()
      })
    },

    //修改参数或者属性面板关闭
    editFormClosed() {
      this.editForm.attr_name = ''
    },

    //文本框失去焦点或者按下回车事件
    async handleInputConfirm(role) {
      if (role.inputValue.trim().length == 0) {
        role.inputVisible = false
        role.inputValue = ''
        return
      } else {
        role.attr_vals.push(role.inputValue)
        role.inputVisible = false
        role.inputValue = ''
        //发送请求, 然后把标签中的内容清空
        const { data: res } = await this.$http.put(`categories/${this.value[2]}/attributes/${role.attr_id}`, {
          attr_name: role.attr_name,
          attr_sel: role.attr_sel,
          attr_vals: role.attr_vals.join(' ')
        })
        console.log(res);
        if (res.meta.status !== 200) return this.$message.error('更新列表失败')
        this.$message.success('更新列表成功')
      }
    },
    showInput(role) {
      role.inputVisible = true
      this.$nextTick((_) => {
        //点击文本框自动获得焦点
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    //当标签被关闭的时候
    handleClose(index, role) {
      role.attr_vals.splice(index, 1)
    },
  },
}
</script>

<style scoped lang="less">
.el-cascader {
  margin: 10px;
}

.el-tag {
  margin: 10px;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
}
</style>
